package com.qmrz.nb.common.domain;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

public class Excel implements Serializable {
    /** 文件名称 */
    private String fileName;
    /** 文件流 */
    private InputStream inputStream;
    /** Sheet */
    private List<ExcelSheet> sheetList;
    /** 文档 */
    private Workbook workbook;

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public List<ExcelSheet> getSheetList() {
        return sheetList;
    }

    public void setSheetList(List<ExcelSheet> sheetList) {
        this.sheetList = sheetList;
    }

    public InputStream getInputStream() {
        return inputStream;
    }

    public void setInputStream(InputStream inputStream) {
        this.inputStream = inputStream;
    }

    public Workbook getWorkbook() {
        return workbook;
    }

    public void setWorkbook(Workbook workbook) {
        this.workbook = workbook;
    }

    public Excel(String fileName) throws IOException {
        this(fileName, null);
    }

    public Excel(String fileName, InputStream inputStream) throws IOException {
        this.fileName = fileName;
        this.inputStream = inputStream;
        this.init();
    }
    /**
    * 是否高版本
     *
    * @author July july_sky@foxmail.com
    * @date 2022/08/14 15:57:24
    */
    public boolean isXSSFWorkbook() {
        String lower = fileName.toLowerCase();
        return !lower.endsWith(".xls") && !lower.endsWith(".docx") && !lower.endsWith(".pptx");
    }

    public void init() throws IOException {
        if (inputStream == null) {
            inputStream = Files.newInputStream(Paths.get(fileName));
        }
        if (this.isXSSFWorkbook()) {
            this.workbook = new XSSFWorkbook(inputStream);
            return;
        }
        this.workbook = new HSSFWorkbook(inputStream);
    }

    public void close() throws IOException {
        this.getWorkbook().close();
    }
}
